import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../views/login.vue'
import Home from '../views/home.vue'
import Vuex from '../store/index.js'
Vue.use(VueRouter)
const routes = [
  // 重定向到登录组件
  { path: '/', redirect: '/login' },
  { path: '/login', component: Login },
  { path: '/home', component: Home }
]
const router = new VueRouter({
  routes
})
// 挂载路由守卫
/**
 * to:去往的路径
 * from:来的路径
 * next:放行函数
 */
router.beforeEach( (to, from, next) => {
  const token = Vuex.state.userInfo.token;
  if (to.path === '/login') return next();
  if (!token) return 'login'
  next()
})

// 暴露出去router
export default router
